import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:oktoast/oktoast.dart';
import '../core/app_initializer.dart';
import '../core/auth/user_manager.dart';
import 'auth_exceptions.dart';
import '../route/routes.dart';
import '../route/route_utils.dart';

import 'app_exceptions.dart';

class GlobalErrorHandler {
  static final GlobalErrorHandler _instance = GlobalErrorHandler._internal();

  factory GlobalErrorHandler() => _instance;

  GlobalErrorHandler._internal();

  final Logger logger = AppInitializer.logger;

  void handleError(dynamic error) {
    String message = '未知错误';

    if (error is DioException) {
      final inner = error.error;
      if (inner is AppException) {
        message = _handleAppException(inner);
      } else if (inner is AuthException) {
        message = _handleAuthException(inner);
      } else {
        message = _handleNetworkError(error);
      }
    } else if (error is AppException) {
      message = _handleAppException(error);
    } else if (error is AuthException) {
      message = _handleAuthException(error);
    } else if (error is Exception) {
      message = error.toString();
    }

    logger.e("GlobalErrorHandler: $message", error: error);
    showToast(message);
  }

  /// 处理业务异常
  String _handleAppException(AppException exception) {
    // 这里可以根据 code 做不同处理
    return exception.message ?? '业务异常';
  }

  /// 处理认证异常
  String _handleAuthException(AuthException exception) {
    // 这里可以根据 code 做不同处理
    if (exception.code == 401) {
      _handleUnauthorized();
    }
    return exception.message ?? '认证失败';
  }

  /// 处理网络异常
  String _handleNetworkError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        return '请求超时，请检查网络';
      case DioExceptionType.badResponse:
        return '服务器返回错误';
      case DioExceptionType.unknown:
        return '网络异常，请检查连接';
      default:
        return error.message ?? '网络错误';
    }
  }

  /// 处理未授权
  void _handleUnauthorized() {
    showToast("登录信息失效，请重新登录。");
    UserManager().clearAll();
    RouteUtils.navigator!
        .pushNamedAndRemoveUntil(RoutePath.login, (route) => false);
  }
}
